﻿using Prism.Commands;
using Prism.Regions;
using Sorting.App.Controls;
using Sorting.App.Core.Mvvm;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using static Sorting.App.Controls.MyMessageBox;
using Sorting.App.Models;
using Sorting.App.Services;
using Sorting.App.Models.Enum;
using Prism.Ioc;
using Sorting.App.Core;
using Modules.Units;
using RabbitMQ;
using Modules.ActionRun;

using MaterialDesignThemes.Wpf;
using Modules.TaskMan.Views;
using Modules.MSentEvent;
using Prism.Events;
using Sorting.App.Models.Model;
using HighPrecisionTimer;
using log4net;
using SortingWorkerService.Handler;
using Sorting.App.Models.Entity;
using System.Windows.Media;
using Microsoft.Xaml.Behaviors.Core;
using System.Windows.Controls;

namespace Modules.TaskMan.ViewModels
{
    public class ViewTaskMainV2ViewModel : RegionViewModelBase
    {
        IContainerExtension _container;
        IEventAggregator _ea;
        private ScanLogService scanLogService = new ScanLogService();
        private ILog log = LogManager.GetLogger(typeof(RabbitMqMessageHandler));
        public ViewTaskMainV2ViewModel(IRegionManager regionManager, IContainerExtension container, IEventAggregator eventPublisher) : base(regionManager)
        {
            _container = container;
            _ea = eventPublisher;
            RealoadShelf();
            //MQHelperFactory.SortingView().SendMsg<RabbitSend<bool>>("SortingView.EquInitial", new RabbitSend<dynamic>
            //{
            //    TaskData = true,
            //    TaskMessage = "任务初始",
            //    TaskType = "任务初始"
            //});
        }


        private ShelfService shelfService = new ShelfService();
        private WardAreaService wardService = new WardAreaService();
        public static List<string> ScanInfo = new List<string>();
        // private bool IsTaskStart = false;

        private DelegateCommand imageMouseUpCmd;
        public ICommand ImageMouseUpCmd => imageMouseUpCmd ??= new DelegateCommand(PerformImageMouseUpCmd);

        private void PerformImageMouseUpCmd()
        {

            this.IsPopOpen = true;
            if (UserName == "未登录")
            {
                LoginInVisibility = "Visible";
                LoginOutVisibility = "Collapsed";
            }
            else
            {
                LoginInVisibility = "Collapsed";
                LoginOutVisibility = "Visible";
            }

        }

        private DelegateCommand login;
        public ICommand LogIn => login ??= new DelegateCommand(PerformLogin);

        private void PerformLogin()
        {

        }

        private DelegateCommand logOut;
        public ICommand LogOut => logOut ??= new DelegateCommand(PerformLogOut);


        /// <summary>
        /// 注销应用
        /// </summary>
        private void PerformLogOut()
        {
            if (BtnStartTxt.ToString() == "停止")
            {
                MessageBoxHelper.ShowDialog<MessageBoxSimpleV2>("请先停止任务");
            }
            var res = MessageBoxHelper.ShowDialog<MessageBoxSimple>(null, "是否确认退出当前用户", "是", "否");
            if (res.Button == MessageBoxResultButton.Yes)
            {
                //执行退出登录，重新回到登录界面   主界面禁用
                //this.AllIsEnable = false;
                //清空登录状态
                AppsettingUnits.CaCheUserInfo = new UserEntity();

                UserName = "未登录";
                //弹出登录窗口
                _ea.GetEvent<LoadingSentEvent>().Publish(3);

            }
        }


        private DelegateCommand sysParamSet;
        public ICommand SysParamSet => sysParamSet ??= new DelegateCommand(PerformSysParamSet);

        /// <summary>
        /// 跳转设备参数维护界面
        /// </summary>
        private void PerformSysParamSet()
        {
            this.IsPopOpen = false;
            this.RegionManager.RequestNavigate(RegionNames.ContentRegion, new Uri("ViewDebug", UriKind.Relative));
        }

        private DelegateCommand sysMain;
        public ICommand SysMain => sysMain ??= new DelegateCommand(PerformSysMain);


        /// <summary>
        /// 弹出系统维护界面
        /// </summary>
        private void PerformSysMain()
        {


            var view = _container.Resolve<ViewSetSysParam>();

            DialogHost.Show(view, "RootDialog");

        }

        private bool isPopOpen = false;

        public bool IsPopOpen
        {
            get => isPopOpen;
            set => SetProperty(ref isPopOpen, value);
        }

        private string loginInVisibility ;
        public string LoginInVisibility
        {
            get => loginInVisibility;
            set => SetProperty(ref loginInVisibility, value);
        }

        private string loginOutVisibility;
        public string LoginOutVisibility
        {
            get => loginOutVisibility;
            set => SetProperty(ref loginOutVisibility, value);
        }


        private string userName = "未登录";

        public string UserName
        {
            get => userName;
            set => SetProperty(ref userName, value);
        }
        private DelegateCommand exitCmd;
        public ICommand ExitCmd => exitCmd ??= new DelegateCommand(PerformExitCmd);

        public List<ShelfJoinWardModel> ShelfEntities { get; set; }
        public List<ShelfJoinWardModel> ShelfEntitiesA { get; set; }
        public List<ShelfJoinWardModel> ShelfEntitiesB { get; set; }

        /// <summary>
        /// 退出
        /// </summary>
        private void PerformExitCmd()
        {
            if (BtnStartTxt.ToString() == "停止")
            {
                TostHelper.ShowWarning("请先停止任务");
                return;
            }

            var res = MessageBoxHelper.ShowDialog<MessageBoxSimple>(null, "是否退出软件", "是", "否");
            if (res.Button == MessageBoxResultButton.Yes)
            {
                MQHelperFactory.SortingView().SendMsg<RabbitSend<bool>>("SortingView.StartStopTask", new RabbitSend<dynamic>
                {
                    TaskData = false,
                    TaskMessage = "任务暂停",
                    TaskType = "任务暂停"
                });
                ActionRunHelper.SelectPlcModelType(EnumPlcModelType.Defult);
                var SortingWorkerService = Process.GetProcessesByName("SortingWorkerService").FirstOrDefault();
                if (SortingWorkerService is not null)
                {
                    SortingWorkerService.Kill();
                }
                Process.GetCurrentProcess().Kill();
                Application.Current.Shutdown();
            }

        }

        //获取信息
        public async Task RealoadShelf()
        {
            var entitys = await shelfService.GetShelves();//调用接口  获取全部的储位信息
            string BatchNo = "";
            if (isCheckOne)
            {
                BatchNo = "1批";
            }
            if (isCheckTwo)
            {
                BatchNo = "2批";
            }
            if (isCheckThree)
            {
                BatchNo = "H5批";
            }
            if (isCheckFour)
            {
                BatchNo = "4批";
            }
            if (isCheckFive)
            {
                BatchNo = "DB3";
            }
            var data = await wardService.GetWardAreas(BatchNo);
            this.ShelfEntities = entitys.ToList();//全部储位信息
            this.ShelfEntitiesA = ShelfEntities.Where(t => t.LeftOrRight.Equals("L")).ToList();//左侧储位信息
            this.ShelfEntitiesB = ShelfEntities.Where(t => t.LeftOrRight.Equals("R")).ToList();//右侧储位信息
            WardArea = data.ToList();//全部病区信息
        }

        private List<WardArea> wardArea;

        public List<WardArea> WardArea { get => wardArea; set => SetProperty(ref wardArea, value); }

        private bool isTaskWating = false;

        public bool IsTaskWating
        {
            get => isTaskWating;
            set => SetProperty(ref isTaskWating, value);
        }

        private DelegateCommand btnStartTask1;
        public ICommand btnStartTask => btnStartTask1 ??= new DelegateCommand(PerformbtnStartTask);

        HPTimer SendTimer = new HPTimer();
        public async void PerformbtnStartTask()
        {
            if (BtnStartTxt.ToString() == "启动")
            {

                //开启按钮加载动画
                this.IsTaskWating = true;
                //通知设备执行服务启动
                MQHelperFactory.SortingView().SendMsg<RabbitSend<bool>>("SortingView.StartStopTask", new RabbitSend<dynamic>
                {
                    TaskData = true,
                    TaskMessage = "任务启动," + AppsettingUnits.CaCheUserInfo.Name,
                    TaskType = "任务启动"
                });
         
                //任务开始标识
                this.IsTaskWating = false;
                //  this.IsTaskStart = true;
                this.BtnStartTxt = "停止";
                TostHelper.ShowSucess("任务启动成功");
                SendTimer.Interval = 500;
                SendTimer.Ticked += SendPTimer_Ticked;
                SendTimer.Start();

            }
            else if (BtnStartTxt.ToString() == "停止")
            {
                //开启按钮加载动画
                this.IsTaskWating = true;
                var mesres = MessageBoxHelper.ShowDialog<MessageBoxSimple>(null, "是否停止任务", "是", "否");
                if (mesres.Button == MessageBoxResultButton.Yes)
                {
                    //通知执行服务关闭
                    MQHelperFactory.SortingView().SendMsg<RabbitSend<bool>>("SortingView.StartStopTask", new RabbitSend<dynamic>
                    {
                        TaskData = false,
                        TaskMessage = "任务暂停",
                        TaskType = "任务暂停"
                    });

                    //任务开始标识
                    this.IsTaskWating = false;
                    //this.IsTaskStart = false;
                    this.BtnStartTxt = "启动";
                    TostHelper.ShowSucess("任务已停止");
                    SendTimer.Ticked -= SendPTimer_Ticked;
                    SendTimer.Stop();
                }
                else
                {
                    this.IsTaskWating = false;
                }
            }
        }
        int x = 0;
        private void SendPTimer_Ticked()
        {
            List<ScanLogDto> ScanInfo = scanLogService.GetScanLog().ToList();//获取扫描日志
            ScanLogDto ScanLog = ScanInfo.FirstOrDefault(s => s.state == "0");
            if (ScanLog != null && x == 0)
            {
                x = 1;
                string wardcode = "";
                //开始处理需要下发的储位执行写入
                var ward = wardService.GetTQWareNoBySnForAsynApi(ScanLog.msg.ToString());//根据扫到的二维码获取对应的病区号 GetWardByBarcode
                if (ward != null)
                    wardcode = ward.WardCode;
                var shelf = shelfService.GetShelfByWardNo(wardcode);//根据病区号获取储位  shelf表
                //NG 就把count++ 更新到界面
                if (shelf == null || shelf.WardArea == "999")
                {
                    AppsettingUnits.ErrorCount++;
                    MQHelperFactory.SortingView().SendMsg<RabbitSend<bool>>("SortingView.ErrorCount", new RabbitSend<dynamic>//把异常数量更新到界面
                    {
                        TaskType = "任务NG",
                        TaskData = AppsettingUnits.ErrorCount,
                        TaskMessage = AppsettingUnits.ErrorCount.ToString()
                    });
                    log.Info(@$"任务下发NG,不清空" + DateTime.Now.ToString());
                    shelf = shelfService.GetShelfByWardNo("999");
                }
                shelf.ScanInfo = ScanLog.msg.ToString();//扫描单号  二维码
                MQHelperFactory.SortingView().SendMsg<RabbitSend<bool>>("Sorting.SendToLoc", new RabbitSend<dynamic>//下发plc 开始运动
                {
                    TaskType = "预备写入队列",
                    TaskData = shelf,
                    TaskMessage = "预备写入队列，下发PLC"

                });
                ScanLog.state = "1";
                scanLogService.UpdateScanLog(ScanLog);//更新扫描日志状态
                x = 0;
            }
        }

        public bool isCheckOne = false;
        public bool isCheckTwo = false;
        public bool isCheckThree = false;
        public bool isCheckFour = false;
        public bool isCheckFive = false;

        private ActionCommand searchCheckCmd;
        public ICommand SearchCheckCmd => searchCheckCmd ??= new ActionCommand(p => PerformSearchCheckCmd(p));
        private void PerformSearchCheckCmd(object p)
        {
            var res = (Button)p;

            switch (res.Tag)
            {

                case "One":
                    isCheckOne = !isCheckOne;
                    res.BorderBrush = isCheckOne ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2ed573"))
                        : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4c7cea"));
                    res.Background = isCheckOne ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2ed573"))
                        : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4c7cea"));
                    GetTaskByFilter();
                    break;
                case "Two":
                    isCheckTwo = !isCheckTwo;
                    res.BorderBrush = isCheckTwo ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2ed573"))
                        : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4c7cea"));
                    res.Background = isCheckTwo ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2ed573"))
                        : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4c7cea"));
                    GetTaskByFilter();
                    break;
                case "Three":
                    isCheckThree = !isCheckThree;
                    res.BorderBrush = isCheckThree ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2ed573"))
                        : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4c7cea"));
                    res.Background = isCheckThree ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2ed573"))
                        : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4c7cea"));
                    GetTaskByFilter();
                    break;
                case "Four":
                    isCheckFour = !isCheckFour;
                    res.BorderBrush = isCheckFour ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2ed573"))
                        : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4c7cea"));
                    res.Background = isCheckFour ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2ed573"))
                        : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4c7cea"));
                    GetTaskByFilter();
                    break;
                case "Five":
                    isCheckFive = !isCheckFive;
                    res.BorderBrush = isCheckFive ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2ed573"))
                        : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4c7cea"));
                    res.Background = isCheckFive ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2ed573"))
                        : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4c7cea"));
                    GetTaskByFilter();
                    break;
                default:
                    break;
            }
        }
        public async void GetTaskByFilter()
        {
            string BatchNo = "";
            if (isCheckOne)
            {
                BatchNo = "1批";
            }
            if (isCheckTwo)
            {
                BatchNo = "2批";
            }
            if (isCheckThree)
            {
                BatchNo = "H5批";
            }
            if (isCheckFour)
            {
                BatchNo = "4批";
            }
            if (isCheckFive)
            {
                BatchNo = "DB3";
            }
            var data = await wardService.GetWardAreas(BatchNo);
            WardArea = data.ToList();
        }

        private object btnStartTxt1 = "启动";

        public object BtnStartTxt { get => btnStartTxt1; set => SetProperty(ref btnStartTxt1, value); }

        private object putCountLab = "已放入：0";

        public object PutCountLab { get => putCountLab; set => SetProperty(ref putCountLab, value); }

        private object sendCountLab = "已下发：0";

        public object SendCountLab { get => sendCountLab; set => SetProperty(ref sendCountLab, value); }

        private object scanCountLab = "已扫描：0";

        public object ScanCountLab { get => scanCountLab; set => SetProperty(ref scanCountLab, value); }

        private object errorCountLab = "异常：0";
        public object ErrorCountLab { get => errorCountLab; set => SetProperty(ref errorCountLab, value); }

        private object labANowTask;

        public object LabANowTask { get => labANowTask; set => SetProperty(ref labANowTask, value); }

        private object labBNowTask;

        public object LabBNowTask { get => labBNowTask; set => SetProperty(ref labBNowTask, value); }
    }
}
